/** Cluster application **/
/* MPPA headers */
#include <mppaipc.h>
#include <mppa/osconfig.h>

//#define MPPA_TRACEPOINT_DEFINE
//#include "test-trace.h"

//#define MPPA_CREATE_TRACEPOINT
//#include "mppa_trace.h"

int usr_C(long int inputC) {    
    int result = 0;
    int i=0;
    while (inputC > 10) {
        i = i + 1;
        inputC = inputC / 2;
        result += i;
    }    
    return result;
}

int usr_A(int inputA) {
    int i;
    long int result = 0;
    for (i = 0; i < inputA; i++) {
        result += i;
    }
    usr_C(result);
    return 1;
}


int usr_B(int inputB) {
    int i;
    long int result = 0;
    for (i = 0; i < inputB; i++) {
        result += i;
    }
    usr_C(50);
    return 1;
}


int usr_main(int input) {
    int result;
    result = usr_A(input);
    int inputB = 10000 - input;
    inputB = inputB / 4;
    result = usr_B(inputB);
    return result;
}

/*
int test()
{
	int a = 10 + 4 * 897;
	int b = testfct(10);
	int c = 2 * 89 /45;
	int d = testfct(100);
	int e = 45/48 + 57;
	int f = testfct(500); 
	return f;
}

int testfct(int x)
{
mppa_tracepoint(test,tp99__in);
	int result = 0;
	int i;
	for (i=0; i < x; i++) result+=i;
mppa_tracepoint(test,tp99__out);
	return result;
}
*/

int main(int argc, char* argv[])
{
//mppa_trace_init();
//mppa_tracepoint(test,tp99__in);
	// get arguments
	int rank = atoi(argv[0]);
        const char *global_sync = argv[1], *results_portal = argv[2];
	
	// set mask (e.g. 1000..0) 
	long long mask = (long long)1 << rank;

	// open Wx connectors	
	int global_sync_fd = mppa_open(global_sync, O_WRONLY);
        int results_portal_fd = mppa_open(results_portal, O_WRONLY);

	// contributes to unblock the I/O, writes on sync with the mask value
	mppa_write(global_sync_fd, &mask, sizeof(mask));

//mppa_trace_init();

// START CODE HERE

    int results;
    int input = 500; // input must be between 0 and 10000
    int i;
    for (i=1; i<112; i+=10) {
        results = usr_main(i);
        long int inputC = 2500;
        int temp = usr_C(inputC);
    }
    
   
	// writes on the portal
	// 	- results_portal_fd = portal descriptor
	// 	- results = data to transfer to the I/O
	// 	- size of data to send
	// 	- position of data on the Rx memory (at I/O)
	

	mppa_pwrite(results_portal_fd, &results, sizeof(long int), sizeof(long int)*rank);
//mppa_tracepoint(test,tp99__out);
}
